//
//  DayCancelViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2018/12/12.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit

class DayCancelViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var surplusCancelNumLabel: UILabel!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    var orderId: String!
    
    var data: Order.CancelReason?
    
    var reasonData = [Order.CancelReason.Reason]()
    
    var selectedReason: Order.CancelReason.Reason?
    
    var orderTime: Int?
    
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            DispatchQueue.global().async {
                let now = Date().timeIntervalSince1970
                if let orderTime = self?.orderTime {
                    var time = Int(now) - orderTime
                    time = time < 0 ? 0 : time
                    let m = time / 60 > 9 ? "\(time / 60)" : "0\(time / 60)"
                    let s = time % 60 > 9 ? "\(time % 60)" : "0\(time % 60)"
                    DispatchQueue.main.async {
                        self?.timeLabel.text = "\(m):\(s)"
                    }
                }
            }
        }
        
        Order.cancelReason(success: { [weak self] data in
            if let data = data {
                self?.data = data
                self?.reasonData = data.cancelReason
                self?.reasonData.append(Order.CancelReason.Reason(cancelReasonId: "-1", reasonName: "其它"))
                
                self?.surplusCancelNumLabel.text = "您今天还有\(data.surplusCancelNum)次取消机会!"
            }
            self?.collectionView.reloadData()
        }) { error in
            p(error)
        }
    }
    
    deinit {
        timer?.invalidate()
        timer = nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return reasonData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ReasonCollectionViewCell
        cell.layer.cornerRadius = 4
        cell.layer.masksToBounds = true
        cell.layer.borderWidth = 1
        
        cell.layer.borderColor = UIColor(red: 221.0/255.0, green: 221.0/255.0, blue: 221.0/255.0, alpha: 1.0).cgColor
        cell.textLabel.textColor = UIColor.black
        cell.layer.backgroundColor = UIColor.white.cgColor
        
        let item = reasonData[indexPath.row]
        
        cell.textLabel.text = item.reasonName
        if item.cancelReasonId == selectedReason?.cancelReasonId {
            cell.layer.borderColor = UIColor(red: 252.0/255.0, green: 166.0/255.0, blue: 72.0/255.0, alpha: 1.0).cgColor
            cell.textLabel.textColor = UIColor.white
            cell.layer.backgroundColor = UIColor(valueRGB: 0xFCA648, alpha: 1.0).cgColor
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedReason = reasonData[indexPath.row]
        collectionView.reloadData()
    }
    
    // MARK: - IBAction
    
    @IBAction func cancel(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func affirm(_ sender: UIButton) {
        guard let reason = selectedReason?.reasonName else {
            showError("请您选择取消原因(1030)")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.cancelPreorder(orderId: orderId, reason: reason, location: userLocation, success: { [weak self] data in
            JZLoading.hideLoading()
            
            guard let data = data else {
                XHProgressHUD.showError("取消失败")
                return
            }
            
            if data.payStatus == 2 {
                self?.performSegue(withIdentifier: "cancelOrderSegue", sender: data)
            } else {
                XHProgressHUD.showSuccess("取消成功")
                self?.navigationController?.popToRootViewController(animated: true)
            }
        }) { error in
            JZLoading.hideLoading()
            XHProgressHUD.showError(error.msg)
        }
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "cancelOrderSegue" {
            if let vc = segue.destination as? CancelOrderPayViewController,
                let preorder = sender as? Order.CancelPreorder {
                vc.orderId = preorder.orderId
                vc.payFee = preorder.payFee
                vc.appointDuration = preorder.appointDuration
            }
        }
    }
}

